<?php

namespace app\logic;

use app\components\helpers\ArrayHelper;
use app\components\helpers\MappingHelper;
use app\components\helpers\ToolsHelper;
use app\forms\RoleForm;
use app\models\Group;
use app\models\Item;
use app\models\Role;
use app\models\RoleItem;
use app\models\RoleItemDefault;
use app\models\UserRole;
use yii;
use yii\db\StaleObjectException;
use yii\helpers\Json;
use yii\web\HttpException;

/**
 * 角色逻辑类
 */
class RoleLogic extends BaseLogic
{
    /**
     * Notes:角色列表
     * Date: 2020/7/22
     * Time: 10:47
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getList($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'index');
        $where = [
            'select' => [
                'r.id',
                'r.name',
                'r.key',
                'r.created_at',
                'r.author_id',
                'r.remark',
                'r.status',
                'u.username as author',
            ],
            'where' => ['and'],
            'pageSize' => $form['pageSize'],
            'orderBy' => 'r.id DESC',
            'User' => 0
        ];
        if ($param['status'] != '') {
            $where['where'][] = ['status' => $param['status']];
        }
        if ($param['name'] != '') {
            $where['where'][] = ['like', 'name', $param['name']];
        }
        $model = new Role();
        $list = $model::getJoinList($where);
        if ($list) {
            $ids = array_column($list, 'id');
            $roleItem = UserRole::getList([
                'select' => ['role_id', 'count(`user_id`) as number'],
                'where' => ['in', 'role_id', $ids],
                'groupBy' => 'role_id'
            ]);
            if ($roleItem) {
                $roleItem = array_column($roleItem, null, 'role_id');
            }
            foreach ($list as &$value) {
                $value['createdAt'] = ToolsHelper::dateFormat($value['created_at']);
                $value['number'] = $roleItem[$value['id']]['number'] ?? 0;
                unset($value['created_at']);
            }
        }
        $list = static::getListReturn($list, $model);
        $list['statusList'] = MappingHelper::statusList();
        return $list;
    }

    /**
     * Notes:创建角色（ 接收表单数据 ）
     * Date: 2020/7/24
     * Time: 17:30
     * @param $param
     * @throws HttpException
     * @throws yii\db\Exception
     */
    public static function create($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'create');
        $data = [
            'key' => mt_rand(100000, 999999),
            'name' => $form['name'],
            'status' => $form['status'],
            'remark' => $form['remark'],
            'author_id' => Yii::$app->getUser()->getId(),
        ];
        $trans = app()->getDb()->beginTransaction();
        $addRole = Role::newCreate($data);
        if ($addRole === false) {
            $trans->rollBack();
        }
        $roleItem = self::_makeUpItem($form);
        pp($roleItem, 1, 1);
        if ($roleItem) {
            $addRoleItem = RoleItem::batchAddData($roleItem);
            if ($addRoleItem === false) {
                $trans->rollBack();
            }
            if ($form['setDefault']) {
                $addRoleItemDefault = RoleItem::batchAddData($roleItem);
                if ($addRoleItemDefault === false) {
                    $trans->rollBack();
                }
            }
        }
        $trans->commit();
        throw new HttpException(200, 'OK');
    }


    /**
     * Notes:权限数据组装
     * Date: 2020/7/24
     * Time: 15:29
     * @param $params
     * @return array
     */
    private static function _makeUpItem($params)
    {
        if (empty($params['item'])) {
            return [];
        }

        $positionItem = $authData = $dataArr = [];

        if (!empty($params['auth'])) {
            $authArr = Json::decode($params['auth']);
            foreach ($authArr as $arr) {
                foreach ($arr as $i => $v) {
                    $authData[$i] = $v;
                }
            }
        }


        if (!empty($params['data'])) {
            $dArr = Json::decode($params['data']);
            foreach ($dArr as $arr) {
                foreach ($arr as $i => $v) {
                    $dataArr[$i] = $v;
                }
            }
        }

        foreach ($params['item'] as $i) {
            $positionItem[] = [
                'type' => isset($authData[$i]) ? $authData[$i] : 0,
                'position_id' => $params['id'],
                'item_id' => $i,
                'data' => isset($dataArr[$i]) ? Json::encode($dataArr[$i]) : ''
            ];
        }
        return $positionItem;
    }

    /**
     * Notes:编辑角色（ 接收表单数据 ）
     * Date: 2020/7/28
     * Time: 9:13
     * @param $param
     * @throws HttpException
     * @throws yii\db\Exception
     */
    public static function update($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'update');
        $data = [
            'key' => mt_rand(100000, 999999),
            'name' => $form['name'],
            'status' => $form['status'],
            'remark' => $form['remark'],
            'author_id' => Yii::$app->getUser()->getId(),
        ];
        $trans = app()->getDb()->beginTransaction();
        $addRole = Role::newCreate($data);
        if ($addRole === false) {
            $trans->rollBack();
        }
        $roleItem = self::_makeUpItem($form);
        if ($roleItem) {
            $delRoleItem = RoleItem::deleteAll(['role_id' => $form['id']]);
            $addRoleItem = RoleItem::batchAddData($roleItem);
            if ($delRoleItem === false || $addRoleItem === false) {
                $trans->rollBack();
            }
            if ($form['setDefault']) {
                $delRoleItemDefault = RoleItemDefault::deleteAll(['role_id' => $form['id']]);
                $addRoleItemDefault = RoleItemDefault::batchAddData($roleItem);
                if ($delRoleItemDefault === false || $addRoleItemDefault === false) {
                    $trans->rollBack();
                }
            }
        }
        $trans->commit();
        throw new HttpException(200, 'OK');
    }

    /**
     * 删除角色
     * @param $param
     * @throws \Throwable
     * @throws StaleObjectException
     */
    public static function delete($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'delete');
        // 删除 角色 及 角色权限
        $role = Role::findDataById($form['id']);
        $delRole = Role::realDeleteById($form['id']);
        $delroleItem = RoleItem::deleteAll(['role_id' => $form['id']]);

        // 是否要判断 角色下有用户不删除  或  将用户的角色重置为空

        // casbin 操作
        throw new HttpException(200, 'OK');
    }

    /**
     * Notes:修改角色状态
     * Date: 2020/7/22
     * Time: 15:31
     * @param $param
     * @throws HttpException
     */
    public static function status($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'status');
        Role::updateByPk(['status' => $form['status']], $form['id']);
        throw new HttpException(200, 'OK');
    }

    /**
     * Notes:授权项下部门授权的数据
     * Date: 2020/7/22
     * Time: 16:54
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getItemData($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'get-item-data');
        $result = RoleItem::getList([
            'select' => ['data'],
            'where' => ['role_id' => $form['id'], 'item_id' => $form['itemId']],
        ]);
        if (!$result) {
            throw new HttpException(423);
        }
        // 解析得到所有的id
        $arr = Json::decode($result['data'][0]);
        $ids = !empty($arr) ? explode(',', $arr['ids']) : [];

        // 获取组织、部门树
        $group = GroupLogic::_getTreeForItemData($ids);
        return ['group' => $group];

    }

    /**
     * 获取角色编辑的信息
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getInfo($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'get-info');
        // 当前角色
        $role = Role::getSingleByPk($form['id'], ['id', 'name', 'remark']);

        // 所有权限项
        $itemArr = ItemLogic::_getItem();
        // 已经赋予的权限项

        $rItems = RoleItem::getList([
            'select' => ['item_id AS id', 'type'],
            'where' => ['role_id' => $form['id']],
        ]);
        $item = PositionLogic::_setItemCheck($itemArr, $rItems);
        return ['role' => $role, 'item' => $item];
    }

    /**
     * 获取角色编辑的信息
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getDefaultItem($param)
    {
        $form = static::_validate(new RoleForm(), $param, 'get-default-item');
        $attr = $form->getAttributes();

        // 所有权限项
        $itemArr = ItemLogic::_getItem();
        // 已经赋予的权限项

        $rItems = RoleItem::getList([
            'select' => ['item_id AS id', 'type'],
            'where' => ['role_id' => $attr['id']],
        ]);
        return PositionLogic::_setItemCheck($itemArr, $rItems);
    }

}